import {Base} from  'base.js';
import {Config} from  'config.js';

class Token{

  constructor(){
    this.verifyUrl = Config.restUrl + 'token/verify';
    this.tokenUrl = Config.restUrl + 'token/user'; 
  }

  verify(){
    var token = wx.getStorageSync('token');
    if(!token){
      this.getTokenFromServer();
    }else{
      this._veifyFromServer(token);
    }
  }

  getTokenFromServer(callback){
     var that = this;
     wx.login({
       success:function(res){
         console.log(res.code);
         wx.request({
           url: that.tokenUrl,
           method:'POST',
           data:{
             code:res.code
           },
           success:function(res){
             wx.setStorageSync('token', res.data.token);
             callback && callback(res.data.token);
           }
         })
       }
     })
  }

  _veifyFromServer(token){
    wx.login({
      success:function(res){
        console.log(res.code);
      }
    })
    var that = this;
    wx.request({
      url: that.verifyUrl,
      data:{
        'token':token
      },
      method:'POST',
      success:function(res){
        var valid = res.data.isValid;
        if(!valid){
          that.getTokenFromServer();
        }
      }
    })
  }

}

export {Token};